//  Android Carpool System
//  2011-2011
//  Author: Jinhuan Wang
//  name: ViewMap.java
//  description: provide a main map view 
//$history: /carpool/scr/com/carpool/ViewMap.java$
/*************************************************/
// add a user define address input dialog 
// Author: Jinhuan Wang Date 2011-5-9
/*************************************************/
// move class DataExchange into ViewMap class
//DataExchange class send xml form front-end app to back-end service
// Author: Jinhuan Wang Date 2011-5-17
/*************************************************/
// remove some parse methed  into Convert.java 
// Author: Jinhuan Wang Date 2011-5-19
/*************************************************/
// remove DataExchange  into com.carpool.request.RequestImpl.java
// Author: Jinhuan Wang Date 2011-5-28
/*************************************************/
package com.carpool;

import java.sql.Date;
import java.util.List;

import android.app.Dialog;
import android.app.ProgressDialog;

import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import com.carpool.AlertDialogFactoty.AlertDialogFactoty;
import com.carpool.driving.DrivingDirections.IDirectionsListener;
import com.carpool.driving.DrivingDirections.Mode;
import com.carpool.driving.Route;
import com.carpool.driving.impl.MyOverlay;
import com.carpool.message.Estimate;
import com.carpool.message.MessageType;
import com.carpool.message.MyGeoPoint;

import com.carpool.message.ReplyMessage;
import com.carpool.message.RequestMessage;
import com.carpool.message.ReverseGeocode;
import com.carpool.message.RouteInfo;
import com.carpool.message.State;
import com.carpool.message.d2sRequest;
import com.carpool.message.s2dReply;
import com.carpool.request.Request;
import com.carpool.request.Request.IRequestListener;
import com.carpool.request.RequestImpl;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

public class ViewMap extends MapActivity implements IDirectionsListener,
		IRequestListener {
	/** private member **/
	private String requirement = null;
	private int capacity = 0;
	private boolean isPublish = false;// in onDirectionsAvailable weather should send to
										// back-end or just drawing
	public ProgressDialog progressBar;
	public ViewMap viewthis = this;
	public MapView mapView = null;
	private MapController mc = null;
	MyOverlay myOverlay = null;
	final private String TAG = "MapView";

	public UserInfo uinfo = null;
	
	int ON_RETURN = -1;
	int ON_RETURN_CHOOSE = 1;
	ReplyMessage m_rpl = null;
	RouteInfo m_rif = null;
	
	String EstimatedDistance = "0";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		mapView = (MapView) findViewById(R.id.map);
		mc = mapView.getController();

		GeoPoint gp = new GeoPoint((int) (30.15 * 1000000),
				(int) (120.16 * 1000000));// HangZhou

		mc.setCenter(gp);
		mc.setZoom(10);
		mapView.setBuiltInZoomControls(true);
		this.uinfo = new UserInfo(this.getApplicationContext());
		progressBar=new ProgressDialog(this);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		Log.i(TAG, "enter onKeyDown");
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		if (id == R.id.SearchMenu) {
			return AlertDialogFactoty.createAlertDialog(viewthis, 2);
		}
		if (id == R.id.PublishMenu) {
			return AlertDialogFactoty.createAlertDialog(viewthis, 1);
		}
		if (id == R.id.EvaluationMenu)
		{
			return AlertDialogFactoty.createAlertDialog(viewthis, 3);
		}
		if (id == R.id.ModeMenu)
		{
			return AlertDialogFactoty.createAlertDialog(viewthis, 4);
		}
		if (id == ON_RETURN) {
			return AlertDialogFactoty.createAlertDialog(viewthis, 0);
		}
		if (id == ON_RETURN_CHOOSE){
			return AlertDialogFactoty.createAlertDialog(viewthis, m_rpl);
		}
		return null;
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		if (id == ON_RETURN) {
			TextView driverName = (TextView) dialog
					.findViewById(R.id.driver_name);
			TextView credit = (TextView) dialog.findViewById(R.id.credit);
			TextView driverPhone = (TextView) dialog
					.findViewById(R.id.driver_phone);
			TextView startSpot = (TextView) dialog
					.findViewById(R.id.start_spot);
			TextView endSpot = (TextView) dialog.findViewById(R.id.end_spot);
			TextView distance = (TextView) dialog
					.findViewById(R.id.estimate_distance);
			TextView amount = (TextView) dialog
					.findViewById(R.id.estimate_money);
			driverName.setText(getString(R.string.driverName)
					+ m_rif.getUsername());
			credit.setText(getString(R.string.credit)
					+ Integer.toString(m_rif.getCredit()));
			driverPhone.setText(getString(R.string.phoneNamer)
					+ m_rif.getNumber());
			String startAddress = ReverseGeocode.parseCoords(m_rif
					.getCStartPoint());
			String endAddress = ReverseGeocode
					.parseCoords(m_rif.getCEndPoint());
			startSpot.setText(getString(R.string.startpoint) + startAddress);
			endSpot.setText(getString(R.string.endpoint) + endAddress);
			Estimate es = new Estimate(m_rif.getCStartPoint(),
					m_rif.getCEndPoint());
			distance.setText(getString(R.string.estimate_distance)
					+ es.estimateDistance() + "Km" + es.estimateTime());
			amount.setText(getString(R.string.estimate_amount)
					+ es.estimateAmount());
		}

	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.ModeMenu:
			showDialog(R.id.ModeMenu);
			break;

		case R.id.SearchMenu: {
			showDialog(R.id.SearchMenu);
			break;
		}
		case R.id.PublishMenu: {
			showDialog(R.id.PublishMenu);
			break;
		}
		case R.id.EvaluationMenu: {
			showDialog(R.id.EvaluationMenu);
			break;
		}
		case R.id.ExitMenu: {

			finish();
			break;
		}
		default:
			break;
		}
		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onDirectionsAvailable(Route route, Mode mode) {
		if (mapView.getOverlays().contains(myOverlay)) {
			mapView.getOverlays().remove(myOverlay);
		}
		myOverlay = new MyOverlay();
		myOverlay.setRoute(route, mode);
		mapView.getOverlays().add(myOverlay);
		if (isPublish == true) {
			RequestMessage pd = new d2sRequest();
			d2sRequest m_R = (d2sRequest) pd;

			m_R.setPostType(false);
			m_R.setUserID(uinfo.getUserID());
			m_R.setRequirement(requirement);
			m_R.setCapacity(capacity);
			Date date = new Date(System.currentTimeMillis());
			List<GeoPoint> r_points = route.getGeoPoints();
			for (int i = 0; i < r_points.size(); i++) {
				MyGeoPoint mGeoPoint = new MyGeoPoint(r_points.get(i), date);
				m_R.addGeoPoints(mGeoPoint);
			}
			// m_R.setDate(new Date(System.currentTimeMillis()));
			Request request = new RequestImpl();
			request.sendMessage(pd, viewthis);
		}
	}

	@Override
	public void onDirectionsNotAvailable() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onReplyAvailable(ReplyMessage rpl) {
		ViewMap.this.m_rpl = rpl;
		if (rpl.getReplyType() == MessageType.passager_reply) {
			progressBar.dismiss();
			showDialog(ON_RETURN_CHOOSE);
		} else if (rpl.getReplyType() == MessageType.passager_reply) {
			if (((s2dReply) rpl).getState() == State.success) {
				Toast.makeText(ViewMap.this, "Publish Success",
						Toast.LENGTH_LONG).show();
			} else if (((s2dReply) rpl).getState() == State.failed) {
				Toast.makeText(ViewMap.this, "Publish failed",
						Toast.LENGTH_LONG).show();
			}
		}
	}

	@Override
	public void onReplyNotAvailable() {
		if (uinfo.getUserType().equals("driver")) {
			Toast.makeText(ViewMap.this, "Publish failed", Toast.LENGTH_LONG)
					.show();
		} else if (uinfo.getUserType().equals("passager") ) {
			progressBar.dismiss();
			Toast.makeText(ViewMap.this, "Oh ,Can't find .Try later.",
					Toast.LENGTH_LONG).show();
		}

	}

	public String getRequirement (){
		return this.requirement;
	}
	public void setRequirement (String req){
		this.requirement=req;
	}
	public int getCapacity(){
		return this.capacity;
	}
	public void setCapacity(int cap){
		this.capacity=cap;
	}
	public boolean IsPublish(){
		return this.isPublish;
	}
	public void setPublish(){
		this.isPublish=true;
	}
	public void setRoute(RouteInfo rif){
		this.m_rif=rif;
	}
	public RouteInfo getRoute(){
		return this.m_rif;
	}
}